/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evolve.webbot.portal;
import  java.io.File;
import  java.io.FileWriter;
import  java.util.List;
import  java.io.BufferedWriter;
import  java.io.FileOutputStream;
import  java.io.FileInputStream;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.io.IOException;
import  java.util.Date;
import  java.util.Iterator;
import  java.util.ArrayList;
import  java.text.SimpleDateFormat;
import  java.util.Properties;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.html.HtmlForm;
import  com.gargoylesoftware.htmlunit.html.HtmlPage;
import  com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput;
import  com.gargoylesoftware.htmlunit.html.HtmlSelect;
import  com.gargoylesoftware.htmlunit.html.HtmlInput;
import  com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import  com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import  javax.swing.JTextArea;
import  com.evolve.webbot.file.CommonErrorFile;
import  com.evolve.webbot.beans.WebBotBeans;
import  com.evolve.webbot.bean.SorianaBean;
import com.evolve.webbot.file.CommonDataFile;
import  com.evolve.webbot.file.TxtSoriana;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import  org.apache.log4j.Logger;


/**
 *
 * @author DarthAE
 */
public class Soriana
{
   private String path;
   private JTextArea jtextArea;
   public static String WB_MAIN_DIR="evolve-webbot";
   public static String SORIANA_MAIN_DIR="soriana-webbot";
   public static String SORIANA_PROP_DIR="soriana-properties";
   public static String SORIANA_PROP_ARC="SorianaPortal.properties";
   public static String SORIANA_FILE_DIR="soriana-files";
   public static String SORIANA_ARC_EXT =".txt";   
   
   public static String SORIANA_ERROR_FILE = "soriana-error-";   
   
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
   
   static Logger log = Logger.getLogger( Soriana.class );

   public Soriana(){}

   public Soriana(String path)
   {
       this.path = path;
   }
   
   public Soriana(String path,JTextArea jtextArea)
   {
       this.path = path;
       this.jtextArea=jtextArea;
   }

   public WebClient creaWebClient()
   {
       WebClient webClient = null;

       webClient = new WebClient();
       webClient.setJavaScriptEnabled(true);
       webClient.setThrowExceptionOnScriptError(false);
       webClient.setAjaxController(new NicelyResynchronizingAjaxController());

       return webClient;
   }

   public WebClient accesoPortal(WebClient webClient,
                                 WebBotBeans webBotBean)
   {
      int indPortalEjec     = 0;
      this.jtextArea.append("\n[+]recuperando archivo soriana");
      String sorianaFilePath = null;
      Properties properties  = new Properties();
      String errorFilePath ="";
      CommonErrorFile   cef = new CommonErrorFile();
      
      try{

           sorianaFilePath= this.path+File.separator+WB_MAIN_DIR+
                                      File.separator+SORIANA_MAIN_DIR+
                                      File.separator+SORIANA_PROP_DIR+
                                      File.separator+SORIANA_PROP_ARC;
           
           log.info("Path Archivos Soriana: "+sorianaFilePath);
           
           
           FileInputStream fis = new FileInputStream(sorianaFilePath);
           

           properties.load(fis);
           
           indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));

           if(indPortalEjec == 1)
           {
               
           try{
                HtmlPage      p = (HtmlPage)webClient.getPage(properties.getProperty("Soriana.UrlLogin"));
                HtmlForm      f = (HtmlForm)p.getFormByName(properties.getProperty("Soriana.FormNameLogin"));
                HtmlTextInput t = (HtmlTextInput)f.getInputByName(properties.getProperty("Soriana.UsrFormName"));
                HtmlPasswordInput pw=(HtmlPasswordInput)f.getInputByName(properties.getProperty("Soriana.PwdFormName"));
            
                List<?> radioList = f.getRadioButtonsByName(properties.getProperty("Soriana.Rb1FormName"));
            
                int k=0;
            
                for (Iterator iter = radioList.iterator(); iter.hasNext();)
                {
                  HtmlRadioButtonInput an2=(HtmlRadioButtonInput)iter.next();

                  an2.setAttribute("value","si");
              
                  if(k>0)
                  {
                       an2.setChecked(true);
                  }
              
                  k++;
                }
            
                t.setValueAttribute(properties.getProperty("Portal.user"));
                pw.setValueAttribute(properties.getProperty("Portal.passwd"));
            
                HtmlInput i =(HtmlInput)f.getInputByName(properties.getProperty("Soriana.SmtFormName"));
                HtmlPage  r =(HtmlPage)i.click();
            
                HtmlPage pg5 =(HtmlPage)webClient.getPage(properties.getProperty("Soriana.UrlCyV"));
                
                log.info(pg5.asText());
                
                List<HtmlAnchor> anchorList = pg5.getAnchors();
                HtmlAnchor an1 = null;
                int l=0;
                
                for (Iterator iter = anchorList.iterator(); iter.hasNext();)
                {
                  an1=(HtmlAnchor)iter.next();

                  if(an1.getAttribute("href").contains("Gen_Env_Arch_Dia") && l<7)
                  {
                      log.info("http://proveedor.soriana.com/sprov/activ/"+an1.getAttribute("href"));
                      String strArcFec=an1.getAttribute("href").substring(an1.getAttribute("href").length() - 8,
                                                                   an1.getAttribute("href").length());
                      
                      InputStream  is  = webClient.getPage("http://proveedor.soriana.com/sprov/activ/"+an1.getAttribute("href")).getWebResponse().getContentAsStream();

                     sorianaFilePath =this.path+File.separator+WB_MAIN_DIR+
                                                File.separator+SORIANA_MAIN_DIR+
                                                File.separator+SORIANA_FILE_DIR+
                                                File.separator+properties.getProperty("Soriana.ArchivoPortal")+"_"+
                                                strArcFec+"_0"+l+SORIANA_ARC_EXT;                      
                      
                      log.info("archivo descargado en "+sorianaFilePath);
                     
                       File file = new File(sorianaFilePath);
                       
                       OutputStream out = new FileOutputStream(file);

                       int read=0;
                       byte[] bytes = new byte[1024];

                       while((read = is.read(bytes))!= -1)
                       {
                           out.write(bytes, 0, read);
                       }

                       is.close();
                       out.flush();
                       out.close();
                       
                       CommonDataFile cdf = new CommonDataFile();
                       cdf.writeCommonWebTxtFileRetail(sorianaFilePath,cdf.readSoriana(sorianaFilePath));
                       this.jtextArea.append("\narchivo ["+l+"] generado: "+sorianaFilePath);
                       l++;
                  }                  
                }
                
//                HtmlForm f1 = (HtmlForm)pg5.getFormByName(properties.getProperty("Soriana.FormNameReport"));
//
//                HtmlSelect s0 =(HtmlSelect)f1.getSelectByName(properties.getProperty("Soriana.Slt0NameReport"));            
//            
//                SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
//                SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
//                SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");
//                String strDateExtract = sdf1.format(webBotBean.getSorianaFBusquedaIni());
//                String dateExtract = sdf1.format(webBotBean.getSorianaFBusquedaIni());
//            
//                this.jtextArea.append("\nfecha de consulta :"+sdf1.format(webBotBean.getSorianaFBusquedaIni()));
//                this.jtextArea.append("\nmes de consulta: "+sdf2.format(webBotBean.getSorianaFBusquedaIni()));
//            
//                s0.setAttribute("option",sdf2.format(webBotBean.getSorianaFBusquedaIni()));
//                s0.setSelectedAttribute(sdf2.format(webBotBean.getSorianaFBusquedaIni()),true);            
//            
//                HtmlSelect s1 =(HtmlSelect)f1.getSelectByName(properties.getProperty("Soriana.Slt1NameReport"));
//                s1.setAttribute("option",dateExtract.substring(6,10));
//            
//                HtmlSelect s2 =(HtmlSelect)f1.getSelectByName(properties.getProperty("Soriana.Slt2NameReport"));
//                s2.setAttribute("option","0");
//                s2.setSelectedAttribute("0", true);
//            
//                HtmlSelect s3 =(HtmlSelect)f1.getSelectByName(properties.getProperty("Soriana.Slt3NameReport"));
//                s3.setAttribute("option","6"); 
//                s3.setSelectedAttribute("6", true);
//            
//                HtmlInput i1 =(HtmlInput)f1.getInputByName(properties.getProperty("Soriana.SmiFormName"));
//                HtmlPage  r3  = (HtmlPage)i1.click();
//            
//                webClient.waitForBackgroundJavaScriptStartingBefore(10000);
//                synchronized (r3) {r3.wait(500);}
//            
//                try{                 
//                     System.out.println(r3.asText());
//                 
//                     sorianaFilePath =this.path+File.separator+WB_MAIN_DIR+
//                                                File.separator+SORIANA_MAIN_DIR+
//                                                File.separator+SORIANA_FILE_DIR+
//                                                File.separator+properties.getProperty("Soriana.ArchivoPortal")+"-"+
//                                                sdf3.format(webBotBean.getSorianaFBusquedaIni())+
//                                                "-mensual"+SORIANA_ARC_EXT;
//                 
//                     BufferedWriter out = new BufferedWriter(new FileWriter(sorianaFilePath));
//
//                     out.write(r3.asText());
//                 
//                     out.flush();
//                     out.close();
//
//                     this.jtextArea.append("\narchivo creado");
//                     this.jtextArea.append("\ngenerando archivo de datos para reporte");
//                 
//                     ArrayList<SorianaBean> sorianaRecordList = new ArrayList<SorianaBean>();
//                     TxtSoriana txtSoriana                    = new TxtSoriana(sorianaFilePath);
//        
//                     sorianaRecordList = txtSoriana.readSorianaTxtFile();
//                     txtSoriana.writeSorianaDataFile(sorianaRecordList);
//                 
//                     this.jtextArea.append("\narchivo de datos generado");
//                 
//                   }catch(IOException ioex){System.out.println(ioex);
//                                            this.jtextArea.append("\nerror al ingresar al portal");
//                                            cef.writeCommonWebTxtFile(errorFilePath,"error al ingresar al portal soriana");                  
//                                            }
 
                   webClient.closeAllWindows();

           }catch(Exception e){System.out.println(e);
                               this.jtextArea.append("\nerror al descargar archivo de datos");
                               cef.writeCommonWebTxtFile(errorFilePath,"error al descargar archivo de datos");
                              }
       }
       else
       if(indPortalEjec == 0)
       {
          this.jtextArea.append("[-]Portal Soriana Desactivado");
          log.info("[-]Portal Soriana Desactivado");           
       }
           
      }catch(Exception e){this.jtextArea.append("\nerror al generar archivo de datos"); 
                          cef.writeCommonWebTxtFile(errorFilePath,"error al generar archivo de datos");
                         } 
      return webClient;
   }   
   
   public void terminaWebClient(WebClient webClient)
   {
       if(webClient!=null)
       {webClient.closeAllWindows();}
   }
}
